package com.kuang.controller.pay;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.kuang.common.anno.IgnoreToken;
import com.kuang.common.base.BaseController;
import com.kuang.config.pay.KsdStaticParameter;
import com.kuang.entity.Product;
import com.kuang.service.ProductService;
import com.kuang.utils.HttpUtils;
import com.kuang.utils.WeixinchatPayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 飞哥yykk
 * 更多学习关注飞哥B站
 * 地址是：https://space.bilibili.com/490711252
 * @title: WeixinPayController
 * @projectName tinyid
 * @description: TODO
 * @date 2021/9/123:00
 */
@RestController
public class WeixinPayController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(WeixinPayController.class);

    @Autowired
    private ProductService productService;


    /**
     * 微信小程序支付
     *
     * @param productId 支付产品
     * @param openid    支付的用户openid
     * @return
     */
    @IgnoreToken
    @PostMapping("/weixinpay")
    public Map<String, Object> weixinpay(String productId, String openid) throws JsonProcessingException {
        if (StringUtils.isEmpty(productId)) {
            throw new IllegalArgumentException("支付的产品找不到!!!");
        }
        // 1: 查询要支付的产品
        Product product = productService.getById(productId);
        if (product == null) {
            throw new IllegalArgumentException("支付的产品找不到!!!");
        }


        Map<String,Object> params = new HashMap<>();
        params.put("mchid",KsdStaticParameter.mchId);
        params.put("appid",KsdStaticParameter.appId);
        params.put("out_trade_no",System.currentTimeMillis()+"");
        params.put("description",product.getProductTitle());
        params.put("notify_url",KsdStaticParameter.notifyUrl);
        Map<String,Object> amountMap = new HashMap<>();
        amountMap.put("total",getMoney(product.getProductPrice()+""));
        amountMap.put("currency","CNY");
        Map<String,Object> payerMap = new HashMap<>();
        payerMap.put("openid",openid);
        params.put("amount", amountMap);
        params.put("payer",payerMap);
        // 发起一个http请求
        ObjectMapper objectMapper = new ObjectMapper();
        String body = objectMapper.writeValueAsString(params);
        log.info("支付的相关参数是：{}", body);
        // 发起http请求
        Map<String, Object> stringObjectMap = HttpUtils.doPostWexin(KsdStaticParameter.unifiedOrderUrlJS, body);
        try {
            HashMap<String, Object> dataMap = WeixinchatPayUtils.getTokenWeixin(KsdStaticParameter.appId, String.valueOf(stringObjectMap.get("prepay_id")));
            return dataMap;
        } catch (Exception ex) {
            return Maps.newHashMap();
        }
    }


    /**
     * 元转换成分
     *
     * @param money
     * @return
     */
    private int getMoney(String money) {
        if (money == null || money.equalsIgnoreCase("0")) {
            return 0;
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = money.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return Integer.parseInt(amLong.toString());
    }

}
